package com.xiaotu.storage.thread;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xiaotu.common.util.FileUtil;
import com.xiaotu.common.util.SepratorUtil;
import com.xiaotu.storage.ACSVStorageProcessor;
import com.xiaotu.storage.model.CacheDataModel;

import net.sf.json.JSONObject;

/**
 * @类名 CSVStorageThread
 * @日期 2017年2月21日
 * @作者 高海军
 * @功能 CSV文件转储线程类
 */
public class CSVStorageThread implements Runnable
{
	private static final Logger LOGGER = LoggerFactory
			.getLogger(CSVStorageThread.class);
	
	private String fileName;
	
	private ACSVStorageProcessor processor;
	
	private Date date;
	
	public CSVStorageThread(String fileName, ACSVStorageProcessor processor,
			Date date)
	{
		super();
		this.fileName = fileName;
		this.processor = processor;
		this.date = date;
	}
	
	@Override
	public void run()
	{
		CacheDataModel cacheData = new CacheDataModel();
		cacheData.setFileName(fileName);
		do
		{
			processor.setRedisData(cacheData, date);
			this.batchProcess(cacheData.getDataList(), fileName, cacheData);
			processor.afterBatch(cacheData);
		}
		while (cacheData.getDataList() != null);
	}
	
	protected void batchProcess(List<JSONObject> list, String fileName,
			CacheDataModel cacheData)
	{
		if (list == null || list.isEmpty())
			return;
		StringBuffer buffer = new StringBuffer();
		String line;
		for (JSONObject target : list)
		{
			line = this.processor.process(target, cacheData, date);
			if (StringUtils.isNotEmpty(line))
			{
				LOGGER.debug("[{}] CSV Line:{}", processor.getTaskType(), line);
				buffer.append(line);
				buffer.append(SepratorUtil.LINE_SEPRATOR);
			}
		}
		if (buffer.length() > 0)
			FileUtil.writeFile(fileName, buffer.toString());
	}
	
}
